<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Exceptions\InvalidRequestException;
use App\Models\ApprovalFlow;
use Illuminate\Support\Facades\Log;

class ApprovalFlowService
{
    public function get($title)
    {
        $sql = ApprovalFlow::when($title, function ($query, $title) {
            return $query->where(function($query) use ($title) {
                $query->where('name','like', '%'.$title.'%');
            });
        });
        return $sql;
    }

    public function insert($input){
        try {
            $data = ApprovalFlow::create($input);
            if($data){
                return $data->id;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function update($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v){
                $res[$k] = $v;
            }
        }
        $res['status'] = $input['status'] == true ? 1 : 0;
        unset($res['id']);
        try {
            $data = ApprovalFlow::where('id',$input['id'])->update($res);
            if($data){
                return $input['id'];
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

}